package com.leetcode;

import ds.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No257
 * @description
 * @date 2021/1/29 下午1:10
 */
public class No257 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode root2 = new TreeNode(2);
        TreeNode root3 = new TreeNode(3);
        TreeNode root4 = new TreeNode(4);
        TreeNode root5 = new TreeNode(5);
        root.left = root2;
        root.right = root3;
        root2.right = root4;
        root3.right = root5;
        List<String> res = binaryTreePaths(root);
        for (int i = 0; i < res.size(); i++) {
            System.out.println(res.get(i));
        }

    }

    public static List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        List<Integer> path = new ArrayList<>();
        getAllPath(root,res,path);
        return res;
        
    }

    private static void getAllPath(TreeNode root, List<String> res, List<Integer> path) {
        if(root == null){
            return;
        }
        path.add(root.val);
        if(isLeaf(root)){
            res.add(convertPath(path));
        }else{
            getAllPath(root.left,res,path);
            getAllPath(root.right,res,path);
        }
        path.remove(path.size() - 1);
    }

    private static String convertPath(List<Integer> res) {
        StringBuilder str = new StringBuilder();
        int len = res.size();

        for (int i = 0; i < len; i++) {
            if(i != 0){
                str.append("->");
            }
            str.append(res.get(i));
        }

        return str.toString();
    }

    private static boolean isLeaf(TreeNode root) {
        return root.left == null && root.right == null;
    }

}
